package edu.sctu.yueding.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.util.ArrayList;
import java.util.List;

import edu.sctu.yueding.R;
import edu.sctu.yueding.activitys.ActivityDetailsActivity;
import edu.sctu.yueding.activitys.ActivityInformationActivity;
import edu.sctu.yueding.adapter.IndexListViewAdapter;
import edu.sctu.yueding.adapter.IndexMatchesAdapter;
import edu.sctu.yueding.adapter.IndexVoteAdapter;
import edu.sctu.yueding.bean.BannerBean;
import edu.sctu.yueding.bean.HomeListViewBean;
import edu.sctu.yueding.bean.IndexMatchesBean;
import edu.sctu.yueding.bean.JsonBaseBeen;
import edu.sctu.yueding.bean.JsonBaseListBean;
import edu.sctu.yueding.bean.MatchBean;
import edu.sctu.yueding.bean.MetaBean;
import edu.sctu.yueding.bean.VoteBean;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.JumpUtils;
import edu.sctu.yueding.utils.UpdateManager;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.SharePreference;
import edu.sctu.yueding.view.MyScrollView;
import edu.sctu.yueding.view.NoSlideListView;
import edu.sctu.yueding.view.banner.ADInfo;
import edu.sctu.yueding.view.banner.ImageCycleView;


/**
 * Created by Administrator on 2016/8/1.
 */
public class IndexFragmentV2 extends Fragment implements View.OnClickListener {


    private Activity mActivity;
    private int newsPage = 0;
    private View view = null;
    private MyScrollView mMyScrollView;
    private ImageCycleView banner;
    private SwipeRefreshLayout mRefreshLayout;
    private ImageView mTopBtn1, mTopBtn2, mTopBtn3;
    private ImageView mCenterBtn1, mCenterBtn2, mCenterBtn3;

    private JsonBaseListBean<HomeListViewBean> newsData = null;
    private JsonBaseListBean<BannerBean> bannerData = null;
    private JsonBaseListBean<IndexMatchesBean> matchesData = null;
    private JsonBaseListBean<VoteBean> voteBean = null;

    private LinearLayout mIncludeLayOne, mIncludeLayTwo;

    private NoSlideListView mListView;

    private int mTopViewHeight;

    private int nowPage = 2;

    private ImageView viewpagerImage;


    private ArrayList<ADInfo> infos = new ArrayList<ADInfo>();

    private IndexListViewAdapter indexNewsAdapter;
    private IndexMatchesAdapter matchesAdapter;
    private IndexVoteAdapter voteAdapter;


    // 要申请的权限
    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS};

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.index_fragment_v2, container, false);
            mActivity = getActivity();
            initView(view);
        }

        isNewest();
        return view;
    }

    private void initBanner() {

        /**
         * banner
         */
        GetVolleyHttp.getInstance(mActivity).getStringGETJsonData(URLConfig.URL_BANNER,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.e("index-------", response);


                        try {

                            bannerData = JSON.parseObject(response, new TypeReference<JsonBaseListBean<BannerBean>>() {
                            }.getType());


                            for (int i = 0; i < bannerData.getData().size(); i++) {

                                ADInfo info = new ADInfo();

                                info.setUrl(bannerData.getData().get(i).getThumbnail());
                                info.setContent(bannerData.getData().get(i).getContent());
                                info.setId(bannerData.getData().get(i).getId());
                                info.setTitle(bannerData.getData().get(i).getTitle());
                                info.setType(bannerData.getData().get(i).getType());

                                infos.add(info);
                            }

                            banner.setImageResources(infos, mAdCycleViewListener);


                        } catch (JSONException exception) {
                            Toast.makeText(mActivity, "网络请求失败", Toast.LENGTH_LONG).show();
                        }

                    }
                }, errorListener, "");

    }

    private ImageCycleView.ImageCycleViewListener mAdCycleViewListener = new ImageCycleView.ImageCycleViewListener() {

        @Override
        public void onImageClick(ADInfo info, int position, View imageView) {

            String type = info.getType();

            try {

                if (type.equals("match")) {

                    GetVolleyHttp.getInstance(mActivity).getStringGETJsonData(
                            URLConfig.URL_ONE_MATCH(info.getId()),
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    JsonBaseBeen<MatchBean> match = JSON.parseObject(response, new TypeReference<JsonBaseBeen<MatchBean>>() {
                                    }.getType());

                                    Bundle bundle = new Bundle();
                                    bundle.putString("matchContent", match.getData().getContent());
                                    SharePreference.getInstance(mActivity).setCache(CacheConfig.CACHE_MATCH_ID, String.valueOf(match.getData().getId()));


                                    if (match.getData().getPrice() == 0.0f)
                                        SharePreference.getInstance(mActivity).setCache(CacheConfig.IS_PRICE, true);
                                    else
                                        SharePreference.getInstance(mActivity).setCache(CacheConfig.IS_PRICE, false);


                                    if (match.getData().getEnrollEnd() < System.currentTimeMillis()) {
                                        //报名结束

                                        bundle.putInt("endTag", ActivityInformationActivity.MATCH_END);
                                    } else {

                                        bundle.putInt("endTag", ActivityInformationActivity.MATCH_NO_END);

                                    }


                                    JumpUtils.jumpActivity(mActivity, ActivityInformationActivity.class, bundle);

                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {

                                }
                            }, "");


                }

                if (type.equals("news")) {

                    final Bundle bundle = new Bundle();

                    bundle.putString(ActivityDetailsActivity.ID_TAG, String.valueOf(info.getId()));

                    JumpUtils.jumpActivity(mActivity, ActivityDetailsActivity.class, bundle);

                    Log.e("newsnewsnews", "sss");

                }


            } catch (NullPointerException e) {

            }

        }

        @Override
        public void displayImage(String imageURL, ImageView imageView) {

            GetVolleyHttp.getInstance(mActivity).setImageLoader(imageView,
                    R.drawable.photo_pictures_no,
                    R.drawable.photo_pictures_no,
                    imageURL);

        }
    };

    @Override
    public void onResume() {
        super.onResume();
        if (bannerData == null){

            initBanner();

        }

        if (newsData == null){

            initNews();
        }

        banner.startImageCycle();
    }

    @Override
    public void onPause() {
        super.onPause();
        banner.pushImageCycle();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        banner.pushImageCycle();
    }

    private void initMatch() {

        GetVolleyHttp.getInstance(mActivity).getStringGETJsonData(URLConfig.URL_HOME_MATCHES + "?page=" + 0 + "&size=10",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        mRefreshLayout.setRefreshing(false);

                        Log.e("index-------", response);

                        try {

                            matchesData = JSON.parseObject(response, new TypeReference<JsonBaseListBean<IndexMatchesBean>>() {
                            }.getType());

                            if (matchesAdapter == null) {

                                matchesAdapter = new IndexMatchesAdapter(mActivity, matchesData.getData());

                            }

                            mListView.setAdapter(matchesAdapter);


                        } catch (JSONException exception) {
                            Toast.makeText(mActivity, "网络请求失败", Toast.LENGTH_LONG).show();
                        }

                    }
                }, errorListener, "");

    }

    private void initNews() {

//        newsPage = 0;

        GetVolleyHttp.getInstance(mActivity).getStringGETJsonData(URLConfig.URL_HOME_LIST + "?page=" + 0,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("index news json", response);


                        mRefreshLayout.setRefreshing(false);

                        try {
                            newsData = JSON.parseObject(response, new TypeReference<JsonBaseListBean<HomeListViewBean>>() {
                            }.getType());

                            if (indexNewsAdapter == null) {
                                indexNewsAdapter = new IndexListViewAdapter(mActivity, newsData.getData());
                            }

                            mListView.setAdapter(indexNewsAdapter);


                        } catch (Exception exception) {
                            Toast.makeText(mActivity, "网络请求失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, errorListenerNews, (long) 5000);
    }

    private void loadMoreNews() {

        newsPage = newsPage + 1;

        GetVolleyHttp.getInstance(mActivity).getStringGETJsonData(URLConfig.URL_HOME_LIST + "?page=" + newsPage,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            newsData = JSON.parseObject(response, new TypeReference<JsonBaseListBean<HomeListViewBean>>() {
                            }.getType());


                            indexNewsAdapter.fresh(newsData.getData(), true);

                        } catch (Exception exception) {
                            Toast.makeText(mActivity, "网络请求失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, errorListener, (long) 5000);
    }

    private void initVote() {

        /**
         * 投票
         */
        GetVolleyHttp.getInstance(mActivity).getStringGETJsonData(URLConfig.URL_HOME_VOTE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String json) {

                        mRefreshLayout.setRefreshing(false);

                        Log.d("vote", json);
                        try {

                            voteBean = JSON.parseObject(json, new TypeReference<JsonBaseListBean<VoteBean>>() {
                            }.getType());

                            MetaBean meta = voteBean.getMeta();

                            if (meta.getCode() == 200 && meta.getErrorType().equals("SUCCESS")) {
                                voteAdapter = new IndexVoteAdapter(mActivity, voteBean.getData());
                            }

                            mListView.setAdapter(voteAdapter);

                        } catch (JSONException exception) {
                            Toast.makeText(mActivity, "网络请求失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, errorListener, "");
    }


    /**
     * 错误  回调
     */
    Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {


        }
    };

    /**
     * 错误  回调
     */
    Response.ErrorListener errorListenerNews = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            if (newsPage != 0) {
                newsPage = newsPage - 1;
            }


        }
    };

    private void initView(View view) {

        mRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.index_fragment_v2_refresh);
        mMyScrollView = (MyScrollView) view.findViewById(R.id.index_fragment_v2_scrollView);
        banner = (ImageCycleView) view.findViewById(R.id.index_fragment_v2_banner);
        mIncludeLayOne = (LinearLayout) view.findViewById(R.id.index_fragment_v2_top_button);
        mIncludeLayTwo = (LinearLayout) view.findViewById(R.id.index_fragment_v2_center_button);

        mTopBtn1 = (ImageView) view.findViewById(R.id.top_btn1);
        mTopBtn2 = (ImageView) view.findViewById(R.id.top_btn2);
        mTopBtn3 = (ImageView) view.findViewById(R.id.top_btn3);

        mCenterBtn1 = (ImageView) view.findViewById(R.id.center_btn1);
        mCenterBtn2 = (ImageView) view.findViewById(R.id.center_btn2);
        mCenterBtn3 = (ImageView) view.findViewById(R.id.center_btn3);

        mTopBtn1.setOnClickListener(this);
        mTopBtn2.setOnClickListener(this);
        mTopBtn3.setOnClickListener(this);

        mCenterBtn1.setOnClickListener(this);
        mCenterBtn2.setOnClickListener(this);
        mCenterBtn3.setOnClickListener(this);

        mIncludeLayOne.setVisibility(View.GONE);

        mListView = (NoSlideListView) view.findViewById(R.id.recyclerView);

        mListView.setFocusable(false);
//
//        ViewGroup.LayoutParams params = mListView.getLayoutParams();
//
//        params.height = 800; //需要设置的listview的高度，你可以设置成一个定值，也可以设置成其他容器的高度，如果是其他容器高度，那么不要在oncreate中执行，需要做延时处理，否则高度为0
//        mListView.setLayoutParams(params);

        initViewHeight();
        settingScrollView();
        
        initOnRefresh();

    }


    private void initViewHeight() {

        ViewTreeObserver bannerVto = banner.getViewTreeObserver();
        bannerVto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                banner.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                mTopViewHeight = mTopViewHeight + banner.getHeight();
            }
        });

        ViewTreeObserver mTopViewHeightVto = mIncludeLayOne.getViewTreeObserver();
        mTopViewHeightVto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mIncludeLayOne.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                mTopViewHeight = mTopViewHeight + mIncludeLayOne.getHeight();
            }
        });


    }

    private void settingScrollView() {

        mMyScrollView.setOnScrollListener(new MyScrollView.OnScrollListener() {
            @Override
            public void onScroll(int scrollY) {

                if (scrollY > mTopViewHeight) {

                    mIncludeLayTwo.setVisibility(View.GONE);
                    mIncludeLayOne.setVisibility(View.VISIBLE);


                } else {

                    mIncludeLayOne.setVisibility(View.GONE);

                    mIncludeLayTwo.setVisibility(View.VISIBLE);
                }
            }
        });


    }


    private void initOnRefresh() {

        mRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);

        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.e("onRefresh", "onRefresh");

                switch (nowPage) {
                    case 1:
                        initMatch();
                        break;
                    case 2:
                        initNews();
                        break;
                    case 3:
                        initVote();
                        break;
                    default:
                        break;
                }


            }
        });

    }

    private void colickAfter(int id) {

        mTopBtn1.setImageResource(R.drawable.index_match);
        mCenterBtn1.setImageResource(R.drawable.index_match);

        mTopBtn2.setImageResource(R.drawable.index_news_);
        mCenterBtn2.setImageResource(R.drawable.index_news_);

        mTopBtn3.setImageResource(R.drawable.index_vote);
        mCenterBtn3.setImageResource(R.drawable.index_vote);


        switch (id) {

            case R.id.top_btn1:
                mTopBtn1.setImageResource(R.drawable.index_match_clicked);
                mCenterBtn1.setImageResource(R.drawable.index_match_clicked);
                break;
            case R.id.top_btn2:
                mTopBtn2.setImageResource(R.drawable.index_news_clicked);
                mCenterBtn2.setImageResource(R.drawable.index_news_clicked);
                break;
            case R.id.top_btn3:

                mTopBtn3.setImageResource(R.drawable.index_vote_clicked);
                mCenterBtn3.setImageResource(R.drawable.index_vote_clicked);
                break;
            default:
                break;

        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.top_btn1:

                nowPage = 1;

                colickAfter(R.id.top_btn1);

                initMatch();

                break;
            case R.id.top_btn2:

                nowPage = 2;

                colickAfter(R.id.top_btn2);

                initNews();

                break;
            case R.id.top_btn3:

                nowPage = 3;

                colickAfter(R.id.top_btn3);

                initVote();

                break;
            case R.id.center_btn1:

                nowPage = 1;

                colickAfter(R.id.top_btn1);

                initMatch();

                break;
            case R.id.center_btn2:

                nowPage = 2;

                colickAfter(R.id.top_btn2);

                initNews();

                break;
            case R.id.center_btn3:

                nowPage = 3;

                colickAfter(R.id.top_btn3);

                initVote();

                break;
            default:
                break;

        }
    }


    /**
     * 版本更新
     */
    private void isNewest() {
        SharePreference sharePreference = SharePreference.getInstance(getActivity());
        if (!sharePreference.getBoolean(CacheConfig.CACHE_IS_CLICK_UPDATE_CANCEL)) {


            // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(mActivity, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有授予该权限，就去提示用户请求
//                        PermissionUtil.showDialogTipUserRequestPermission(mActivity, permissions);
                    ActivityCompat.requestPermissions(mActivity, permissions, 321);

                } else {
                    new UpdateManager(getActivity()).checkUpdate();//true
                }

            } else {
                new UpdateManager(getActivity()).checkUpdate();//true
            }
        }
    }


}

